#Blade Chronicle MDL parser

import os, sys
from Sanae3D.lib.ModelObject import Model3D
from Sanae3D.lib.StructReader import StructReader

class BladeChronicle_MDL(Model3D):
    
    def __init__(self, obj3D=None, outFile=None, inFile=None):
        
        super(BladeChronicle_MDL,self).__init__("MDL")
        self.obj3D = obj3D
        self.inFile = inFile
        self.outFile = outFile
        
    def parse_file(self, filename):
        '''Main parser method. Can be replaced'''
        
        meshName = filename
        self.create_object(meshName)
        
        magic = self.inFile.read_string(4)
        self.inFile.read_long(2)
        self.inFile.seek(4, 1)
        self.inFile.read_float(10)
        self.inFile.read_long(2)
        numVerts = self.inFile.read_long()
        self.inFile.read_long() #0x24
        numFaces = self.inFile.read_long() / 3
        self.inFile.read_long(4)
        
        for i in range(numVerts):
            vx, vy, vz = self.inFile.read_float(3)
            nx, ny, nz = self.inFile.read_float(3)
            unk = self.inFile.read_long()
            tu, tv = self.inFile.read_float(2)
            self.create_vertex(meshName, i)
            self.add_coords(meshName, i, [vx, vy, vz])
            self.add_vert_normals(meshName, i, [nx, ny, nz])
            self.add_vert_uv(meshName, i, [tu, tv])
            
        for i in range(numFaces):
            
            v1, v2, v3 = self.inFile.read_short(3)
            self.create_face(meshName, i)
            self.add_face_verts(meshName, i, [v1, v2, v3])        
            
def read_file(path):
    '''Read the file'''
    
    filename, ext = os.path.splitext(os.path.basename(path))
    openFile = StructReader(open(path, 'rb'))
    obj = BladeChronicle_MDL(inFile=openFile)
    obj.parse_file(filename)
    openFile.close()
    return obj

def write_file(path):
    
    pass

def definitions():
    '''Return the header, extension, and a description of the format'''
    
    return "mdl", "MDL", "Blade Chronicles MDL"

if __name__ == '__main__':
    
    file1 = "000_001_07005.mdl"
    obj = read_file(file1)